package com.fzrskj.cloud.free.core.tool;

import ms.core.tool.CookieTool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * CCookieTool.
 *
 * @author zj.
 *         Created on 2018/9/3 0003.
 */
public class CCookieTool extends CookieTool {
    public static void refreshSessionId(HttpServletRequest request, HttpServletResponse response, String sid){
        String s = getCookieValue(request,CONST_SESSIONID);
        if (CStrTool.isBlankStr(s))
            setCookieValue(response, CONST_SESSIONID, sid);
    }

    /**to get cookie from httpRequest by cookie id
     * @param request
     * @param cookieName cookie name of value
     * @return null if cookie not exists, otherwise return value of cookie
     */
    private static String getCookieValue(HttpServletRequest request, String cookieName){
        String value=null;
        Cookie[] cookies = request.getCookies();
        if (cookies==null)
            return value;

        for(Cookie ck: cookies){
            if (ck.getName().equals(cookieName)){
                value = ck.getValue();
                break;
            }
        }
        return value;
    }

    /**set cookie value to httpResponse
     * @param response response to client
     * @param cookieName cookie name to set
     * @param value cookie value of cookie name
     * by lms 2016.08.28
     */
    private static void setCookieValue(HttpServletResponse response, String cookieName, String value){
        Cookie ck = new Cookie(cookieName,value);
        response.addCookie(ck);
    }
}
